"use client";

import * as React from "react";

import { AIChatPlugin } from "@platejs/ai/react";
import {
  BLOCK_CONTEXT_MENU_ID,
  BlockMenuPlugin,
  BlockSelectionPlugin,
} from "@platejs/selection/react";
import { KEYS } from "platejs";
import { useEditorPlugin, usePlateState } from "platejs/react";

import { useIsTouchDevice } from "@/components/plate/hooks/use-is-touch-device";
import {
  ContextMenu,
  ContextMenuContent,
  ContextMenuGroup,
  ContextMenuItem,
  ContextMenuSub,
  ContextMenuSubContent,
  ContextMenuSubTrigger,
  ContextMenuTrigger,
} from "@/components/plate/ui/context-menu";

type Value = "askAI" | null;

export function BlockContextMenu({ children }: { children: React.ReactNode }) {
  const { api, editor } = useEditorPlugin(BlockMenuPlugin);
  const [value, setValue] = React.useState&lt;Value&gt;(null);
  const isTouch = useIsTouchDevice();
  const [readOnly] = usePlateState("readOnly");

  const handleTurnInto = React.useCallback(
    (type: string) =&gt; {
      editor
        .getApi(BlockSelectionPlugin)
        .blockSelection.getNodes()
        .forEach(([node, path]) =&gt; {
          if (node[KEYS.listType]) {
            editor.tf.unsetNodes([KEYS.listType, "indent"], {
              at: path,
            });
          }

          editor.tf.toggleBlock(type, { at: path });
        });
    },
    [editor],
  );

  const handleAlign = React.useCallback(
    (align: "center" | "left" | "right") =&gt; {
      editor
        .getTransforms(BlockSelectionPlugin)
        .blockSelection.setNodes({ align });
    },
    [editor],
  );

  if (isTouch) {
    return children;
  }

  return (
    &lt;ContextMenu
      onOpenChange={(open) =&gt; {
        if (!open) {
          // prevent unselect the block selection
          setTimeout(() =&gt; {
            api.blockMenu.hide();
          }, 0);
        }
      }}
      modal={false}
    &gt;
      &lt;ContextMenuTrigger
        asChild
        onContextMenu={(event) =&gt; {
          const dataset = (event.target as HTMLElement).dataset;

          const disabled = dataset?.slateEditor === "true" || readOnly;

          if (disabled) return event.preventDefault();

          api.blockMenu.show(BLOCK_CONTEXT_MENU_ID, {
            x: event.clientX,
            y: event.clientY,
          });
        }}
      &gt;
        <div>{children}</div>
      &lt;/ContextMenuTrigger&gt;
      &lt;ContextMenuContent
        className="w-64"
        onCloseAutoFocus={(e) =&gt; {
          e.preventDefault();
          editor.getApi(BlockSelectionPlugin).blockSelection.focus();

          if (value === "askAI") {
            editor.getApi(AIChatPlugin).aiChat.show();
          }

          setValue(null);
        }}
      &gt;
        &lt;ContextMenuGroup&gt;
          &lt;ContextMenuItem
            onClick={() =&gt; {
              setValue("askAI");
            }}
          &gt;
            Ask AI
          &lt;/ContextMenuItem&gt;
          &lt;ContextMenuItem
            onClick={() =&gt; {
              editor
                .getTransforms(BlockSelectionPlugin)
                .blockSelection.removeNodes();
              editor.tf.focus();
            }}
          &gt;
            Delete
          &lt;/ContextMenuItem&gt;
          &lt;ContextMenuItem
            onClick={() =&gt; {
              editor
                .getTransforms(BlockSelectionPlugin)
                .blockSelection.duplicate();
            }}
          &gt;
            Duplicate
            {/* &lt;ContextMenuShortcut&gt;⌘ + D&lt;/ContextMenuShortcut&gt; */}
          &lt;/ContextMenuItem&gt;
          &lt;ContextMenuSub&gt;
            &lt;ContextMenuSubTrigger&gt;Turn into&lt;/ContextMenuSubTrigger&gt;
            &lt;ContextMenuSubContent className="w-48"&gt;
              &lt;ContextMenuItem onClick={() =&gt; handleTurnInto(KEYS.p)}&gt;
                Paragraph
              &lt;/ContextMenuItem&gt;

              &lt;ContextMenuItem onClick={() =&gt; handleTurnInto(KEYS.h1)}&gt;
                Heading 1
              &lt;/ContextMenuItem&gt;
              &lt;ContextMenuItem onClick={() =&gt; handleTurnInto(KEYS.h2)}&gt;
                Heading 2
              &lt;/ContextMenuItem&gt;
              &lt;ContextMenuItem onClick={() =&gt; handleTurnInto(KEYS.h3)}&gt;
                Heading 3
              &lt;/ContextMenuItem&gt;
              &lt;ContextMenuItem onClick={() =&gt; handleTurnInto(KEYS.blockquote)}&gt;
                Blockquote
              &lt;/ContextMenuItem&gt;
            &lt;/ContextMenuSubContent&gt;
          &lt;/ContextMenuSub&gt;
        &lt;/ContextMenuGroup&gt;

        &lt;ContextMenuGroup&gt;
          &lt;ContextMenuItem
            onClick={() =&gt;
              editor
                .getTransforms(BlockSelectionPlugin)
                .blockSelection.setIndent(1)
            }
          &gt;
            Indent
          &lt;/ContextMenuItem&gt;
          &lt;ContextMenuItem
            onClick={() =&gt;
              editor
                .getTransforms(BlockSelectionPlugin)
                .blockSelection.setIndent(-1)
            }
          &gt;
            Outdent
          &lt;/ContextMenuItem&gt;
          &lt;ContextMenuSub&gt;
            &lt;ContextMenuSubTrigger&gt;Align&lt;/ContextMenuSubTrigger&gt;
            &lt;ContextMenuSubContent className="w-48"&gt;
              &lt;ContextMenuItem onClick={() =&gt; handleAlign("left")}&gt;
                Left
              &lt;/ContextMenuItem&gt;
              &lt;ContextMenuItem onClick={() =&gt; handleAlign("center")}&gt;
                Center
              &lt;/ContextMenuItem&gt;
              &lt;ContextMenuItem onClick={() =&gt; handleAlign("right")}&gt;
                Right
              &lt;/ContextMenuItem&gt;
            &lt;/ContextMenuSubContent&gt;
          &lt;/ContextMenuSub&gt;
        &lt;/ContextMenuGroup&gt;
      &lt;/ContextMenuContent&gt;
    &lt;/ContextMenu&gt;
  );
}
